<?php

namespace app\api\model\cps;

use app\api\model\ExtendConsume;
use app\api\model\UserConsumeLog;
use app\common\model\User;
use app\shopapi\model\ExtendConsumeShop;

require_once ROOT_PATH.'extend/ali-sdk/TopSdk.php';
require_once ROOT_PATH.'extend/ali-sdk/top/TopClient.php';
require_once ROOT_PATH.'extend/ali-sdk/top/request/AlibabaAlscUnionElemePromotionStorepromotionQueryRequest.php';
require_once ROOT_PATH.'extend/ali-sdk/top/domain/PromotionQueryRequest.php';
require_once ROOT_PATH.'extend/ali-sdk/top/request/AlibabaAlscUnionElemePromotionStorepromotionGetRequest.php';
require_once ROOT_PATH.'extend/ali-sdk/top/domain/SingleStorePromotionRequest.php';
require_once ROOT_PATH.'extend/ali-sdk/top/request/AlibabaAlscUnionElemePromotionOfficialactivityGetRequest.php';
require_once ROOT_PATH.'extend/ali-sdk/top/domain/ActivityRequest.php';
require_once ROOT_PATH.'extend/ali-sdk/top/request/AlibabaAlscUnionKbcpxPositiveOrderGetRequest.php';
require_once ROOT_PATH.'extend/ali-sdk/top/request/AlibabaAlscUnionElemeStorepromotionReviewbwcStockLockRequest.php';
require_once ROOT_PATH.'extend/ali-sdk/top/request/AlibabaAlscUnionElemeStorepromotionReviewbwcStockReleaseRequest.php';
require_once ROOT_PATH.'extend/ali-sdk/top/request/AlibabaAlscUnionMediaZoneAddRequest.php';

//饿了么联盟接口
class Elm
{
    protected $appkey = '34748608';

    protected $secret = '5971095b9c2c9ace757cd60b82d78b1c';

    protected $pid = 'alsc_27756062_8185001_21287100';

    //推广店铺列表
    public function shoplist($longitude,$latitude,$activity='false')
    {
        $c = new \TopClient();
        $c->appkey = $this->appkey;
        $c->secretKey = $this->secret;

        $req = new \AlibabaAlscUnionElemePromotionStorepromotionQueryRequest;
        $query_request = new \PromotionQueryRequest;

        $query_request->pid=$this->pid;
        $query_request->sort_type='distance';
        $query_request->in_activity=$activity;
        $query_request->longitude=$longitude;
        $query_request->latitude=$latitude;

       /* $query_request->session_id="8497813e6deb4bddac841aca76e3bf8a";
        $query_request->in_activity="false";
        $query_request->has_bonus_stock="false";
        $query_request->min_commission_rate="0.01";
        $query_request->page_size="20";
        $query_request->biz_type="activityCps|ordinaryCps";
        $query_request->search_content="";
        $query_request->include_dynamic="true";*/
        $req->setQueryRequest(json_encode($query_request));
        $resp = $c->execute($req);
        //dump($resp->data->records->store_promotion_dto);die;
        /*foreach ($resp->data->records as $k=>$v){
            $detail = $this->shopdetail($pid,$v['shop_id']);
            dump($detail);die;
        }*/
        return $resp->data;
    }

    //推广店铺详情
    public function shopdetail($shop_id)
    {
        $c = new \TopClient();
        $c->appkey = $this->appkey;
        $c->secretKey = $this->secret;

        $req = new \AlibabaAlscUnionElemePromotionStorepromotionGetRequest;
        $query_request = new \SingleStorePromotionRequest;

        $query_request->pid=$this->pid;
        $query_request->shop_id=$shop_id;

        $req->setQueryRequest(json_encode($query_request));
        $resp = $c->execute($req);

        return $resp->data;
    }

    //推广活动查询
    public function activity($activity_id,$user_id)
    {
        $c = new \TopClient();
        $c->appkey = $this->appkey;
        $c->secretKey = $this->secret;

        $user = User::get($user_id);
        if ($user->elm_pid){
            $pid = $user->elm_pid;
        } else {
            $pid = $this->createPid($user_id);
            $user->elm_pid = $pid;
            $user->save();
        }

        $req = new \AlibabaAlscUnionElemePromotionOfficialactivityGetRequest;
        $query_request = new \ActivityRequest;
        $query_request->pid=$pid;
        $query_request->activity_id=$activity_id;
        $query_request->sid=$user_id;
        $query_request->include_wx_img="true";
        $query_request->include_qr_code="true";
        $req->setQueryRequest(json_encode($query_request));
        $resp = $c->execute($req);

        return $resp->data;
    }

    //创建推广位
    public function createPid($user_id)
    {
        $user = User::get($user_id);
        $c = new \TopClient();
        $c->appkey = $this->appkey;
        $c->secretKey = $this->secret;

        $req = new \AlibabaAlscUnionMediaZoneAddRequest;
        $req->setZoneName($user->mobile);
        //$req->setMediaId("1");
        $resp = $c->execute($req);
        return $resp->result->pid;
    }

    //查询未结算的订单
    public function unliquidated()
    {
        $lists = UserConsumeLog::where(['cps_type'=>4,'consume_type'=>2,'is_to_account'=>0])->field('pay_time')->select();

        foreach ($lists as $k=>$v){
            $start = date('Y-m-01 00:00:00',$v['pay_time']);
            $end = date('Y-m-d H:i:s',$v['pay_time']);
            $res = $this->order(1,$start,$end);
        }
    }

    //订单列表
    public function order($type=0,$start='',$end='')
    {
        $c = new \TopClient();
        $c->appkey = $this->appkey;
        $c->secretKey = $this->secret;
        $req = new \AlibabaAlscUnionKbcpxPositiveOrderGetRequest;
        $start_date = date('Y-m-01 00:00:00');
        //$end_date = date('Y-m-d H:i:s',time());
        if ($type==1){
            $start_date = $start;
            //$end_date = $end;
        }
        $req->setDateType("1");
        //$req->setSettleState("1");
        //$req->setEndDate($end_date);
        $req->setBizUnit("2");
        $req->setPageSize("50");
        $req->setPageNumber("1");
        $req->setStartDate($start_date);
        //$req->setPid($this->pid);
        $resp = $c->execute($req);

        if (isset($resp->result->order_detail_report_d_t_o)){
            $order_list = $resp->result->order_detail_report_d_t_o;

            //dump($order_list);die;
            foreach ($order_list as $k=>$v){

                //增加消费记录
                $user = User::get(['elm_pid'=>$v->pid]);

                if ($user){

                    if ($user->level==1||$user->level==2){
                        $commission = $v->income*0.2;
                    } elseif($user->level==3) {
                        $commission = $v->income*0.68;
                    }

                    $consume_log_info = UserConsumeLog::get([ 'user_id'=>$user->id, 'order_no'=>$v->parent_order_id]);
                    if (!$consume_log_info){
                        $consume_log_model = new UserConsumeLog();
                        $consume_log_data = [
                            'user_id'=>$user->id,
                            'title'=>$v->title,
                            'shop_id'=>0,
                            'shop_name'=>'饿了么',
                            'image'=>$v->pic_url,
                            'order_no'=>$v->parent_order_id,
                            'pay_time'=>strtotime($v->pay_time),
                            'pay_price'=>$v->pay_amount,
                            'consume_type'=>2,
                            'cps_type'=>4,
                            'goods_id'=>$v->item_id,
                            'commission'=>$commission,
                            'total_commission'=>$v->income,
                            'order_status_name'=>'已付款'
                        ];
                        User::update(['is_buy'=>1],['id'=>$user->id]);
                        $user_model = new User();
                        $user_model->upgrade($user->id);
                        $consume_log_model->save($consume_log_data);
                        //计算推广收益
                        UserConsumeLog::waimaiCouponConsumeCalculate($user->id,$consume_log_model->total_commission,$consume_log_model->consume_id);

                    } else {
                        if ($v->order_state==4&&$consume_log_info->is_to_account==0){
                            //发放消费记录的收益
                            UserConsumeLog::sendCommission($consume_log_info->order_no);
                        } elseif($v->order_state==0&&$consume_log_info->is_refund==0) {
                            $consume_log_info->commission = 0;
                            $consume_log_info->order_status_name = '退款成功';
                            $consume_log_info->is_refund = 1;
                            $consume_log_info->save();
                            ExtendConsume::update(['commission'=>0],['consume_log_id'=>$consume_log_info->consume_id]);
                            ExtendConsumeShop::update(['commission'=>0],['consume_log_id'=>$consume_log_info->consume_id]);
                        }
                    }
                }


            }

            return $order_list;
        } else {
            return  [];
        }

    }


}